<template>
	<view class="container" :style="appThemeStyle">
		<!-- 店铺页面组件 -->
		<Page :items="items" ref="pageIndexContent" :city="city" :address="address" :selectedCity="selectedCity" :isLogin="isLogin" />
		<!-- 用户隐私保护提示（仅微信小程序） -->
		<!-- #ifdef MP-WEIXIN -->
		<PrivacyPopup :hideTabBar="true" />
		<!-- #endif -->
	</view>
</template>

<script>
import { setCartTabBadge, checkLogin } from '@/core/app';
import * as Api from '@/api/page';
import Page from '@/components/page';
import PrivacyPopup from '@/components/privacy-popup';
const App = getApp();

export default {
	components: {
		Page,
		PrivacyPopup
	},
	data() {
		return {
			// 页面参数
			options: {},
			// 页面属性
			page: {},
			// 页面元素
			items: [],
			city: '',
			address: '',
			citySelector: null,
			selectedCity: {
				cityName: '',
				cityCode: ''
			},
			isLogin: false
		};
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		// 当前页面参数
		this.options = options;
		// 加载页面数据
		this.getPageData();
		//获取定位
		if (!this.selectedCity.cityCode && !App.globalData.selectedCity) {
			this.$refs.pageIndexContent.handleNewAddress();
		}
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {
		// 更新购物车角标
		setCartTabBadge();
		if (App.globalData.selectedCity) {
			this.selectedCity = { ...App.globalData.selectedCity };
		}

		this.citySelector = requirePlugin('citySelector');
		const data = this.citySelector.getCity(); // 选择城市后返回城市信息对象，若未选择返回nul
		if (data) {
			this.selectedCity.cityName = data.fullname;
			this.selectedCity.cityCode = data.id;
			// 修改属性（直接赋值）
			App.globalData.selectedCity = { ...this.selectedCity };
		}
		console.log(this.selectedCity);
		// 判断是否已登录
		this.isLogin = checkLogin();
	},

	onUnload() {
		// 页面卸载时清空插件数据，防止再次进入页面，getCity返回的是上次的结果
		this.citySelector.clearCity();
	},
	methods: {
		/**
		 * 加载页面数据
		 * @param {Object} callback
		 */
		getPageData(callback) {
			const app = this;
			const pageId = app.options.pageId || 0;
			Api.detail(pageId)
				.then((result) => {
					// 设置页面数据
					const {
						data: { pageData }
					} = result;
					app.page = pageData.page;
					app.items = pageData.items;
				})
				.finally(() => callback && callback());
		}
	},

	/**
	 * 下拉刷新
	 */
	onPullDownRefresh() {
		// 获取首页数据
		this.getPageData(() => {
			uni.stopPullDownRefresh();
		});
	},

	/**
	 * 分享当前页面
	 */
	onShareAppMessage() {
		const app = this;
		const { page } = app;
		return {
			title: page.params.shareTitle,
			path: '/pages/index/index?' + app.$getShareUrlParams()
		};
	},

	/**
	 * 分享到朋友圈
	 * 本接口为 Beta 版本，暂只在 Android 平台支持，详见分享到朋友圈 (Beta)
	 * https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share-timeline.html
	 */
	onShareTimeline() {
		const app = this;
		const { page } = app;
		return {
			title: page.params.shareTitle,
			path: '/pages/index/index?' + app.$getShareUrlParams()
		};
	}
};
</script>

<style lang="scss" scoped>
.container {
	background: #f7f7f7;
}
</style>
